package com.so206.crond.process;

import com.so206.plugins.pay.AliPayFunction;
import com.so206.plugins.pay.WxPayFunction;
import com.so206.po.*;
import com.so206.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class SettPaymentThread implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(SettPaymentThread.class);

    private SettLementService settLementService;

    private UserService userService;

    private AliPayFunction aliPayFunction;

    private WxPayFunction wxPayFunctionPC;

    private WebConfigService webConfigService;

    private PayConfigService payConfigService;

    private AlipayConfigService alipayConfigService;

    private WxPayConfigService wxPayConfigService;

    private Integer run_mode;

    public SettPaymentThread(SettLementService settLementService, UserService userService, AliPayFunction aliPayFunction, WxPayFunction wxPayFunctionPC, WebConfigService webConfigService, PayConfigService payConfigService, AlipayConfigService alipayConfigService, WxPayConfigService wxPayConfigService, Integer run_mode) {
        this.settLementService = settLementService;
        this.userService = userService;
        this.aliPayFunction = aliPayFunction;
        this.wxPayFunctionPC = wxPayFunctionPC;
        this.webConfigService = webConfigService;
        this.payConfigService = payConfigService;
        this.alipayConfigService = alipayConfigService;
        this.wxPayConfigService = wxPayConfigService;
        this.run_mode = run_mode;
        logger.info("打款线程启动...");
    }

    @Override
    public void run() {
        logger.info("开始结算用户打款...");
        if (run_mode == 1) {
            //手动结算
            this.sett_process();
        } else {
            //系统自动打款
            SystemWeb config = webConfigService.find_by_id(1L);
            if (config.getAutoSettlePay() == 1) {
                this.sett_process();
            } else {
                logger.info("系统没有开启自动打款功能!");
            }
        }
        logger.info("打款结算完毕...");
    }

    /**
     * 打款处理
     */
    private void sett_process() {
        SystemPayConfig payConfig = payConfigService.getPayConfig(1L);
        Long trAlipay = payConfig.getTrAlipay();
        AlipayConfig config_tr = alipayConfigService.find_by_id(trAlipay);
        WxpayConfig wx_pay_config = wxPayConfigService.find_by_id(payConfig.getTrWxpay());
        WxpayConfig wx_pay_config_card = wxPayConfigService.find_by_id(payConfig.getTrWxpayCard());
        List<SystemSett> slist = settLementService.findAllSett(1);
        if (slist != null && slist.size() > 0) {
            for (SystemSett sysSettExt : slist) {
                SystemUser user = userService.findUserById(sysSettExt.getUid());
                Integer paytype = user.getZspaytype();
                if (paytype == 1) {
                    Boolean money = null;
                    try {
                        money = wxPayFunctionPC.changeMoneyToWxAccount(sysSettExt, user, wx_pay_config.getAppId(), wx_pay_config.getPid(), wx_pay_config.getPublicKeyMch(), wx_pay_config.getWxCert());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    logger.info("微信打款:用户:" + user.getUser() + " PID:" + user.getId() +
                            " 金额:" + sysSettExt.getSettFinalMoney() + " 状态:" + money);
                } else if (paytype == 2) {
                    Boolean money = aliPayFunction.changeMoneyToAccount(sysSettExt, user, config_tr.getAppId(), config_tr.getPrivateKey(), config_tr.getPublicKey());
                    logger.info("支付宝打款: 用户:" + user.getUser() + " PID:" + user.getId() +
                            " 金额:" + sysSettExt.getSettFinalMoney() + " 状态:" + money);
                } else if (paytype == 4) {
                    HashMap<String, String> param = new HashMap<>();
                    param.put("str", UUID.randomUUID().toString().replaceAll("-", "").substring(0, 31));
                    param.put("sid", sysSettExt.getSid());
                    param.put("pid", user.getZspayid());
                    param.put("pname", user.getZsname());
                    param.put("title", "转账:" + sysSettExt.getSid());
                    param.put("bank", user.getCardBankCode());
                    param.put("final_money", String.valueOf(sysSettExt.getSettFinalMoney()));
                    Map ret = null;
                    try {
                        ret = wxPayFunctionPC.payToUserCard(param, wx_pay_config_card.getAppId(), wx_pay_config_card.getPid(), wx_pay_config_card.getPublicKeyMch(), wx_pay_config_card.getWxCert());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Object error = ret.get("error");
                    Integer status = new Integer(ret.get("status").toString());
                    Object tran_no = ret.get("tran_no");
                    if (status == 2) {
                        sysSettExt.setStatus(2);
                        sysSettExt.setTranNo(String.valueOf(tran_no));
                        sysSettExt.setSettError(String.valueOf(error));
                        settLementService.updateSystemSett(sysSettExt);
                        logger.info("支付宝打款: 用户:" + user.getUser() + " PID:" + user.getId() +
                                " 金额:" + sysSettExt.getSettFinalMoney() + " 状态:true");
                    } else {
                        sysSettExt.setStatus(3);
                        sysSettExt.setTranNo(String.valueOf(tran_no));
                        sysSettExt.setSettError(String.valueOf(error));
                        settLementService.updateSystemSett(sysSettExt);
                        logger.info("支付宝打款: 用户:" + user.getUser() + " PID:" + user.getId() +
                                " 金额:" + sysSettExt.getSettFinalMoney() + " 状态:false");
                    }
                }
            }
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<SystemSett> slist2 = settLementService.findAllSett(3);
        if (slist2 != null && slist2.size() > 0) {
            for (SystemSett sysSettExt : slist2) {
                SystemUser user = userService.findUserById(sysSettExt.getUid());
                Integer paytype = user.getZspaytype();
                if (paytype == 1) {
                    Boolean money = null;
                    try {
                        money = wxPayFunctionPC.changeMoneyToWxAccount(sysSettExt, user, wx_pay_config.getAppId(), wx_pay_config.getPid(), wx_pay_config.getPublicKeyMch(), wx_pay_config.getWxCert());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    logger.info("微信打款:用户:" + user.getUser() + " PID:" + user.getId() +
                            " 金额:" + sysSettExt.getSettFinalMoney() + " 状态:" + money);
                } else if (paytype == 2) {
                    Boolean money = aliPayFunction.changeMoneyToAccount(sysSettExt, user, config_tr.getAppId(), config_tr.getPrivateKey(), config_tr.getPublicKey());
                    logger.info("支付宝打款: 用户:" + user.getUser() + " PID:" + user.getId() +
                            " 金额:" + sysSettExt.getSettFinalMoney() + " 状态:" + money);
                } else if (paytype == 4) {
                    HashMap<String, String> param = new HashMap<>();
                    param.put("str", UUID.randomUUID().toString().replaceAll("-", "").substring(0, 31));
                    param.put("sid", sysSettExt.getSid());
                    param.put("pid", user.getZspayid());
                    param.put("pname", user.getZsname());
                    param.put("title", "转账:" + sysSettExt.getSid());
                    param.put("bank", user.getCardBankCode());
                    param.put("final_money", String.valueOf(sysSettExt.getSettFinalMoney()));
                    Map ret = null;
                    try {
                        ret = wxPayFunctionPC.payToUserCard(param, wx_pay_config_card.getAppId(), wx_pay_config_card.getPid(), wx_pay_config_card.getPublicKeyMch(), wx_pay_config_card.getWxCert());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Object error = ret.get("error");
                    Integer status = new Integer(ret.get("status").toString());
                    Object tran_no = ret.get("tran_no");
                    if (status == 2) {
                        sysSettExt.setStatus(2);
                        sysSettExt.setTranNo(String.valueOf(tran_no));
                        sysSettExt.setSettError(String.valueOf(error));
                        settLementService.updateSystemSett(sysSettExt);
                        logger.info("支付宝打款: 用户:" + user.getUser() + " PID:" + user.getId() +
                                " 金额:" + sysSettExt.getSettFinalMoney() + " 状态:true");
                    } else {
                        sysSettExt.setStatus(3);
                        sysSettExt.setTranNo(String.valueOf(tran_no));
                        sysSettExt.setSettError(String.valueOf(error));
                        settLementService.updateSystemSett(sysSettExt);
                        logger.info("支付宝打款: 用户:" + user.getUser() + " PID:" + user.getId() +
                                " 金额:" + sysSettExt.getSettFinalMoney() + " 状态:false");
                    }
                }
            }
        }
    }

}
